package com.bleeth.fx.component;

import cn.hutool.core.util.StrUtil;
import com.bleeth.fx.helper.SStyleHelper;
import com.bleeth.fx.helper.StyleHelper;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import lombok.Builder;

/**
 * @author Sakura
 * @version 1.0
 * @date 2021-11-13 22:17
 **/
@Builder
public class MIconTextField {

    @Builder.Default
    private String searchIcon = "icon-search";

    @Builder.Default
    private String removeIcon = "icon-remove";


    @Builder.Default
    private double width = 300;

    @Builder.Default
    private double height = 30;

    @Builder.Default
    private double iconSize = 20;

    @Builder.Default
    private String placeholder = "";

    private double radius;

    public Region make() {
        Region leftIcon = MIcon.builder().icon(searchIcon).size(20).build().make();
        TextField textField = new TextField();
        textField.setPrefWidth(width - 20 * 2);
        Region cleanIcon = MIcon.builder().icon(removeIcon).size(20).build().make();

        HBox box = new HBox();
        box.setPrefSize(width, height);
        box.setAlignment(Pos.CENTER_LEFT);
        box.getChildren().addAll(leftIcon, textField, cleanIcon);
        box.setPadding(new Insets(0, height / 4, 0, height / 4));

        //box设置边框
        if (radius == 0) {
            radius = height / 2;
        }
        SStyleHelper.node(box)
                .addStyle("-fx-border-color", "#1f202488")
                .addStyle("-fx-border-style", "SOLID")
                .addStyle("-fx-border-width", 1)
                .addStyle("-fx-border-radius ", radius)
                .apply();

        cleanIcon.setVisible(false);
        textField.setPromptText(placeholder);
        SStyleHelper.node(textField)
                .addStyle("-fx-background-color", "#f4f4f4")
                .addStyle("-fx-font-size", 14)
                .apply();


        //添加cleanIcon操作事件
        cleanIcon.setOnMouseClicked(event -> {
            textField.clear();
        });

        textField.textProperty().addListener((observable, oldValue, newValue) -> {
            if (StrUtil.isEmpty(newValue)) {
                cleanIcon.setVisible(false);
                return;
            }
            if (StrUtil.isEmpty(oldValue) && StrUtil.isNotEmpty(newValue)) {
                cleanIcon.setVisible(true);
            }
        });

        textField.focusedProperty().addListener((observable, oldValue, newValue) -> {
            if (textField.isFocused()) {
                StyleHelper.br(box).radius(radius).width(1).color("#409eff").style("SOLID").make();
            } else {
                StyleHelper.br(box).radius(radius).width(1).color("#1f202488").style("SOLID").make();
            }
        });
        return box;
    }


}
